<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\BlackCard\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\BlackCard\BlackAccount;
use Doraemon\model\BlackCard\BlackOrder;
use Doraemon\model\BlackCard\CloudAccount;
use Doraemon\service\BlackCard\IncomeOrder;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Tab;


class OrderController extends Controller
{
    public function index(Content $content, Request $request)
    {
        Admin::script($this->reloadScript());
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page');
        $order_no = $request->input('order_no');
        $selector_params = $request->input("_selector");
        $o_status = ($selector_params && isset($selector_params['o_status'])) ? $selector_params['o_status'] : 0;
        $limit = [
            ($page - 1) * $perPage, $perPage
        ];
        $query = ($o_status) ? ['o_status' => $o_status] : [];
        if ($order_no){
            $query['order_no'] = $order_no;
        }

        $result = IncomeOrder::getList($limit, $query);
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'per_page' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) use ($order_no) {
                $grid->disableExport();
                $grid->disableRowSelector();

                //筛选
                $grid->filter(function (Grid\Filter $filter) use ($order_no) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($order_no) {
                        $filter->equal('order_no', '订单编号')->default($order_no);
                    });

                    //条件展开
                    if ($order_no) $filter->expand();
                });


                $grid->column("id", 'id');
                $grid->column("order_no", '订单编号');
                $grid->column("uid", '用户uid');
                // 黑卡卡号处可弹出，展示云账户信息
                $grid->column('black_no', '黑卡会员号')->modal('云账户信息', function ($model) {
                    $cloud_info = CloudAccount::getCloudAccount($this->uid);
                    return new Table(['用户名', '手机号', '云账户账号'], [['username' => $cloud_info['username'], 'telephone' => $cloud_info['telephone'], 'cloud_no' => $cloud_info['cloud_no']]]);
                });

                $grid->column("pic_url", '订单封面图')->image($this->pic_url, 100, 100);
                $grid->column("goods_title", '商品标题');
                $grid->column("buy_num", '商品数量');
                $grid->column("o_from_type", '订单来源')->display(function () {
                    return BlackOrder::O_FROM_TYPE_MAP[$this->o_from_type];
                });

                // 当状态为未入账，已入账时，可以更改返佣佣金
                $grid->column("rate_amount", '返佣金额(元)')->width(100)->display(function ($rate_amount, $column){
                    if (in_array($this->o_status, [BlackOrder::TYPE_STATUS_UNRECORD, BlackOrder::TYPE_STATUS_RECORD])){
                        return $column->editable();
                    } else {
                        return $rate_amount;
                    }
                });

                $grid->column("o_status", '订单状态')->display(function () {
                    return BlackOrder::TYPE_STATUS_MAP[$this->o_status];
                });

//                $grid->disableActions();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    $actions->disableEdit();
                    if ($actions->row['o_status'] == BlackOrder::TYPE_STATUS_COMMIT) {
                        $actions->append('<a class="fa reloadJoin" data-o_status="4" data-id="'.$this->row["id"].'" href="javascript:;">标记为转账</a>');
                    }

                    if (in_array($actions->row['o_status'], [
                        BlackOrder::TYPE_STATUS_UNRECORD,
                        BlackOrder::TYPE_STATUS_RECORD,
                        BlackOrder::TYPE_STATUS_COMMIT
                    ])){
                        $actions->append('<a class=\'btn order_refresh btn-xs btn-success fa grid-check-row\' data-id="'.$this->row["id"].'">刷新</a>');
                    }
                });

                $grid->selector(function (Grid\Tools\Selector $selector) {
                    $selector->selectOne('o_status', '订单状态', array_merge([0 => "全部"], BlackOrder::TYPE_STATUS_MAP));
                });
            });

        $content->row($gridList);
        return $content
            ->header('返佣订单列表')
            ->description(' ')
            ->breadcrumb(['text' => 'order']);
    }

    private function reloadScript()
    {
        return <<<SCRIPT
        $('.reloadJoin').unbind('click').click(function(){
            var id = $(this).data('id');
            var o_status = $(this).data('o_status');
            let url = id  + '/setStatus'
            let params = {"o_status":o_status}
            layer.confirm('是否已转账？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                toastr.success('更新任务已经添加,稍后查看');
                $.post(url, params, function( data ) {
                    location.reload();
                });
            });            
        });
        
        $('.order_refresh').unbind('click').click(function(){
            var id = $(this).data('id');
            let url = id  + '/refresh'
            let params = {}
            layer.confirm('是否要刷新？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                toastr.success('更新任务已经添加,稍后查看');
                $.post(url, params, function( data ) {
                    location.reload();
                });
            });            
        });
SCRIPT;
    }

    public static function setStatus(Request $request, Content $content, $id)
    {
        $request = $request->all();
        // 更新状态
        BlackOrder::updateData(["o_status" => $request['o_status']], ["id" => $id]);
    }


    public static function refresh(Request $request, Content $content, $id)
    {
        $order_info = BlackOrder::getOrderInfo($id);
        if (in_array($order_info['o_status'], [BlackOrder::TYPE_STATUS_UNRECORD, BlackOrder::TYPE_STATUS_RECORD])){
            if ($order_info['o_from_type'] == BlackOrder::O_FROM_TYPE_JIEXUAN){
                $o_status = \Doraemon\service\BlackCard\IncomeOrder::getJieXuanOrderStatus($order_info['order_no'], $order_info['goods_id']);
            } else {
                $o_status = \Doraemon\service\BlackCard\IncomeOrder::getYouzanOrderStatus($order_info['order_no'], $order_info['goods_id']);
            }
            $res = BlackOrder::updateData(["o_status" => $o_status], ["id" => $order_info['id']]);
        }
    }

    // 编辑
    public function create(Request $request,Content $content)
    {
        $request = $request->all();

        $data = [];
        $form = new Form($data);
        $form->text('order_no', '订单编号')->setWidth(4, 2)->required('不能为空');
        $form->text('black_no', '设计师黑卡会员号')->setWidth(4, 2)->required('不能为空');
        $form->radio('o_from_type', '订单来源')->options(BlackOrder::O_FROM_TYPE_MAP)->default(BlackOrder::O_FROM_TYPE_YOUZAN);
        $form->action('/admin/blackCard/order/orderSubmit');
        $form_body = $form->render();

        return $content
            ->header('黑卡返佣订单 - 添加')
            ->body($form_body);
    }

    // 编辑
    public function orderSubmit(Request $request,Content $content)
    {
        $params = $request->all();
        if (!BlackAccount::hasExistBlackNo($params['black_no'])){
            $error = new MessageBag([
                'title' => "黑卡卡号不存在"
            ]);

            return back()->with(compact('error'));
        }

        // 查询是否已添加相同订单号订单
        $db_order_list = BlackOrder::selectByWhere(["order_no" => $params['order_no']]);
        if ($db_order_list && is_array($db_order_list)){
            $error = new MessageBag([
                'title' => "该订单号已经添加，不能重复添加。"
            ]);
            return back()->with(compact('error'));
        }


        // 获取订单信息
        if ($params['o_from_type'] == BlackOrder::O_FROM_TYPE_JIEXUAN){
            $order_info = IncomeOrder::getJieXuanOrderInfo($params['order_no']);
        } else {
            $order_info = IncomeOrder::getYouzanOrderInfo($params['order_no']);
        }
        if (empty($order_info)){
            $error = new MessageBag([
                'title' => "没有查询到对应订单"
            ]);

            return back()->with(compact('error'));
        }

        $black_info = BlackAccount::getBlackAccountInfoByBlackNo($params['black_no']);
        foreach ($order_info['goods_list'] as $goods_info){
            $income_order_info = [
                "uid" => $black_info['uid'],
                "o_from_type" => $params['o_from_type'],
                "order_no" => $params['order_no'],
                "goods_title" => $goods_info['goods_title'],
                "pic_url" => $goods_info['pic_url'],
                "buy_num" => $goods_info['buy_num'],
                "goods_id" => $goods_info['goods_id'],
                "rate_amount" => $goods_info['rate_amount'],
                "o_status" => $goods_info['o_status'],
            ];

            // 添加订单
            BlackOrder::insertData($income_order_info);
        }

        $success = new MessageBag([
            'title' => '操作成功'
        ]);

        return redirect('/admin/blackCard/order/index')->with(compact('success'));
    }

    public static function changeRateAmount(Request $request, Content $content, $id)
    {
        $name = $request->input('name', '');
        $value = $request->input('value', 0);
        try {
            if (!is_float($value)) {
                BlackOrder::updateData(['rate_amount' => $value], ['id' => $id]);
                return response()->json([
                    'status' => true,
                ]);
            } else {
                throw new \Exception('参数错误');
            }
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }

}